package com.zhang.websocket;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.RemoteEndpoint;
import java.io.IOException;

/**
 * @Author LongYi
 * @Date 2022/4/20 17:42
 * @Description
 */
@Slf4j
public class WebSocketUtil {



    /**
     * 后端发送消息给前端
     *
     * @param remoteEndpoint
     * @param msg
     */
    public static void sendMsg(RemoteEndpoint.Basic remoteEndpoint, String msg) {
        msg = getLimitStr(msg, 2000);
        if (remoteEndpoint != null) {
            WebSocketResponse message = new WebSocketResponse();
            message.setType("info");
            message.setMsg((DateTime.now().toDateStr()) + "：" + msg);
            String text = JSON.toJSONString(message, SerializerFeature.WriteMapNullValue);
            try {
                remoteEndpoint.sendText(text);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.debug(msg);
    }

    /**
     * 后端发送数据给前端
     *
     * @param remoteEndpoint
     * @param data
     * @param <T>
     */
    public static <T> void sendData(RemoteEndpoint.Basic remoteEndpoint, T data) {
        if (remoteEndpoint != null) {
            WebSocketResponse message = new WebSocketResponse();
            message.setType("data");
            message.setData(data);
            String text = JSON.toJSONString(message, SerializerFeature.WriteMapNullValue);
            try {
                remoteEndpoint.sendText(text);
                log.debug("websocket返回对象：" + text);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 字符串限制长度
     *
     * @param str
     * @param maxLen
     * @return
     */
    public static String getLimitStr(String str, int maxLen) {
        if (str != null && str.length() > maxLen) {
            str = str.substring(0, maxLen) + "......";
        }
        return str;
    }
}
